package com.itc.access.server.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.itc.access.server.VideoServer;
import com.itc.common.core.constant.CacheConstants;
import com.itc.common.core.domain.R;
import com.itc.common.core.utils.OkHttpUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.stereotype.Service;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.net.ssl.*;
import java.security.cert.X509Certificate;

@Service
public class VideoServerImpl implements VideoServer {

    private String username = "ythzdykdj";
    private String password = "Ythzdykdj@123";
//    private String loginUrl = "https://10.48.221.66:18531"+"/loginInfo/login/v1.0";
    private String loginUrl = "https://10.48.221.66:9900"+"/loginInfo/login/v1.0";
//    private String routingUrl = "https://10.48.221.66:18531"+"/device/domainRoute/v1.1";
//    private String routingUrl = "https://10.48.221.66:18531"+"/device/domainroute";
    private String routingUrl = "https://10.48.221.66:9900"+"/device/domainroute";

    /**
    /**
     * 根据域路由信息，获取摄像机信息
     * @return
     */
    public R getCameraInfo(){
        return R.ok();
    }

    /**
     * 根据登录token，获取域路由
     * @return
     */
    public R domainRouting(){
        R token = userLogin();
        System.out.println("获取域路由开始");
        String cookie = (String) token.getData();
        System.out.println("cookie为："+cookie);
        if (cookie == null || cookie.isEmpty()) {
            return R.fail("登录失败，未获取到Token");
        }

        try {
            // 创建URL对象
            URL url = new URL(routingUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 设置请求头
            String jsessionId = null;
            if (cookie != null && cookie.startsWith("JSESSIONID")) {
                // 只保留 JSESSIONID=... 的部分
                jsessionId = cookie.split(";")[0];
            }

            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            // 使用简化后的 JSESSIONID 设置 Cookie 请求头
            if (jsessionId != null) {
                connection.setRequestProperty("Cookie", jsessionId);
                System.out.println("Cookie 请求头: " + jsessionId);
            } else {
                System.out.println("JSESSIONID 未找到或无效.");
            }

            // 打印请求头信息
            Map<String, List<String>> requestProperties = connection.getRequestProperties();
            for (Map.Entry<String, List<String>> entry : requestProperties.entrySet()) {
                System.out.println("请求头: " + entry.getKey() + " = " + entry.getValue());
            }

            // 获取响应代码
            int responseCode = connection.getResponseCode();
            System.out.println("响应代码: " + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 打印响应内容
            System.out.println("响应内容: " + response.toString());

            // 断开连接
            connection.disconnect();

            return R.ok(response.toString());

        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("请求失败");
        }
    }

    @Override
    public R logout(String cookie) {


        return null;
    }

    /**
     * 登录获取响应头中的token
     * @return
     */
    public R userLogin(){
        String result = "";
        try {
            // 创建URL对象
            URL url = new URL(loginUrl);
            // 打开与目标URL的连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 允许向连接输出数据
            connection.setDoOutput(true);

            // 设置请求属性（请求头）
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            // 准备请求体数据
            String jsonInputString = "{\"userName\": \"" + username + "\", \"password\": \"" + password + "\"}";

            // 写入请求体数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应代码以触发请求
            int responseCode = connection.getResponseCode();
            System.out.println("响应代码: " + responseCode);

            // 获取响应头中的Set-Cookie
//            Map<String, List<String>> headers = connection.getHeaderFields();
            Map<String, List<String>> headers = connection.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                System.out.println("响应头: " + entry.getKey() + " = " + entry.getValue());
            }
            List<String> cookies = headers.get("Set-Cookie");

            // 打印所有的Set-Cookie信息
            if (cookies != null) {
                for (String cookie : cookies) {
                    System.out.println("Set-Cookie: " + cookie);
                    result = cookie;
                }
            } else {
                System.out.println("响应中未找到Set-Cookie.");
            }

            // 断开连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }

//        JSONObject paramJson = new com.alibaba.fastjson.JSONObject();
//        paramJson.put("userName",username);
//        paramJson.put("password",password);
//        RequestBody body = RequestBody.create(paramJson.toJSONString(), MediaType.parse("application/json"));
//        Map<String, String> headers = new HashedMap<>();
//        headers.put("Content-Type", "application/json;charset=UTF-8");
//        Object resultObj = OkHttpUtil.sendOkHttpClientHeader(loginUrl, "POST",body,headers,"Set-Cookie");
//        System.out.println(JSONUtil.parse(resultObj));
//        result = String.valueOf(JSONUtil.parse(resultObj));

        return R.ok(result);
    }

    public VideoServerImpl() {
        // 跳过证书验证
        trustAllCertificates();
    }

    /**
     * 信任所有证书
     */
    private void trustAllCertificates() {
        try {
            // 创建一个信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                    }
            };

            // 设置SSLContext为使用上述TrustManager
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 创建一个HostName验证器，信任所有主机名
            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
